import { io } from 'socket.io-client'

export default function initWebSocket (config = {}) {
  let socket = null
  return new Promise((resolve, reject) => {
    socket = io(config.url || '/ws', {
      pingTimeout: 10000, // 10秒后无响应则认为服务器不可用
      pingInterval: 5000,  // 每5秒发送一次心跳
      // transports: ['polling','websocket'],
      timeout: config.timeout || 300000,
      reconnectionDelayMax: config.reconnectionDelayMax || 10000,
      reconnectionDelay: config.reconnectionDelay || 5000,
      // path:"/ws"
    })
    socket.on('connect', () => {
      console.log("socket connect success.")
      console.log(`socketio客户端id: ${socket.id}`)
      resolve(socket)
    })
    socket.on('disconnect', () => {
      console.log("socket is disconnect.")
    })

    socket.on('message', data => {
      if (data.event) {
        config.onMessage = config.onMessage || function () { console.log(data) }
        config.onMessage(data)
      }
    })
    socket.connect()

  })
}


